package com.manage.base.controller;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.Assert;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BaseController
		implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

	protected static ObjectMapper mapper = new ObjectMapper();

	protected <T> T fromJson(String json, Class<T> clazz) {
		return gson.fromJson(json, clazz);
	}

	// 获取基于应用程序的url绝对路径
	public final String getAppbaseUrl(HttpServletRequest request, String url) {
		Assert.hasLength(url, "url不能为空");
		Assert.isTrue(url.startsWith("/"), "必须以/打头");
		return request.getContextPath() + url;
	}

	protected String getWebRootPath(HttpServletRequest request) {
		return request.getServletContext().getRealPath("");
	}

	protected String getWebRootUrl(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length())
				.append(request.getServletContext().getContextPath()).append("/").toString();
		return tempContextUrl;
	}
}
